package com.ebt.m.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Rick.Wang on 2016/3/17.
 */
public class SortKeyUtil {

    public static final StringBuilder sb0 = new StringBuilder();
    public static final StringBuilder sb1 = new StringBuilder();
    public static final StringBuilder sb2 = new StringBuilder();

    public static final String chReg = "[\\u4E00-\\u9FA5]";
    public static final Pattern pattern = Pattern.compile(chReg);
    public static Matcher matcher;

    /**
     * 根据sortkey返回经过归类的sortkey(只适合这种形式：String sortKey = "XIAN 县 YI 医 YUAN 院 ZONG 总 JI 机";)
     * 		stringArray[0] = "县医院总机"
     * 		stringArray[1] = "XIANYIYUANZONGJI"
     * 		stringArray[2] = "XYYZJ"
     * 	三个元素均不为空
     * @param sortKey
     * @param stringArray
     * @return
     */
    public static String[] classifySortKey(String sortKey, String[] stringArray){
        if(stringArray == null){
            stringArray = new String[3];
        }

        sb0.setLength(0);//清空汉字
        sb1.setLength(0);//清空全拼
        sb2.setLength(0);//清空简拼

        matcher = pattern.matcher(sortKey);

        matcher.lookingAt();
        while(matcher.find()){
            sb0.append(matcher.group(0));
        }
        stringArray[0] = sb0.toString();//汉字

        String[] enStrs = sortKey.replace(" ", "").split(chReg);
        for (int i = 0, length = enStrs.length; i < length; i++) {
            if (enStrs[i].length() > 0) {
                sb1.append(enStrs[i]);//全拼
                sb2.append(enStrs[i].charAt(0));//简拼
            }
        }
        stringArray[1] = sb1.toString();//汉字
        stringArray[2] = sb2.toString();//汉字

        return stringArray;
    }

    /**
     * 示例程序
     */
    public static void test(){

        String sortKey0 = "XIAN 县 YI 医 YUAN 院 ZONG 总 JI 机";
        String[] sortKey0Array = classifySortKey(sortKey0, null);
        for(int i = 0; i < sortKey0Array.length; i++){
            System.out.println(sortKey0Array[i]);
        }
        System.out.println("========");

        String sortKey1 = "email";
        String[] sortKey1Array = classifySortKey(sortKey1, null);
        for(int i = 0; i < sortKey1Array.length; i++){
            System.out.println(sortKey1Array[i]);
        }
    }

}
